var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp();

Page({
  data: {
    addressList: [],
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    if (util.session == undefined) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
    }else{
      this.getAddressList();
    }
    
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示

  },
  getAddressList (){
    let that = this;
    util.request(api.showUserAddress, { openId: util.session}).then(function (res) {
      if (res == null) {
        that.setData({
          addressList: []
        })
      }else{
        that.setData({
          addressList: res
        })
      }
    });
  },
  addressAddOrUpdate (event) {
    if (util.session == undefined) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
    } else {
     wx.navigateTo({
      url: '/pages/ucenter/addressAdd/addressAdd?id=' + event.currentTarget.dataset.addressId
    })
    }

  },
  deleteAddress(event){
    console.log(event.target)
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要删除地址？',
      success: function (res) {
        if (res.confirm) {
          let addressId = event.target.dataset.addressId;
          util.request(api.delAddress, { addressId: addressId }, 'GET').then(function (res) {
            wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 1000
            })
            util.request(api.showUserAddress, { openId: util.session }).then(function (res2) {
              if(res2 == null){
                that.setData({
                  addressList:[]
                })
              } else {
                that.setData({
                  addressList: res2
                })
              }
            });
          });
        }
      }
    })
    return false;
    
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})